import { message } from 'antd'
import 'whatwg-fetch'
import * as ES6Promise from 'es6-promise';
import { createHashHistory } from 'history';
import axios from 'axios'

ES6Promise.polyfill();

function obj2params(obj) {
  let result = ''
  Object.keys(obj).forEach((key) => {
    result += `&${key}=${encodeURIComponent(obj[key])}`;
  })

  return result.substr(1)
}
const host = process.env.API_BASE || ''
// get请求
export function get(baseUrl, params, headersParam) {
  const url = `${host}${baseUrl}?${obj2params(params)}`;
  const headers = Object.assign({}, {
    Accept: 'application/json, text/plain, */*',
  }, headersParam);
  const result = axios({
    url,
    headers,
  })
  return result;
}
export function post(baseUrl, params, headersParam) {
  const url = `${host}${baseUrl}`;
  const headers = Object.assign({}, {
    Accept: 'application/json, text/plain, */*',
  }, headersParam);
  const result = axios({
    method: 'post',
    url,
    headers,
    data: params,
  })
  return result;
}
export function clearStorage() {
  try {
    window.localStorage.removeItem('ReactNews_UserInfo');
  } catch (e) {

  }
}
export class REQUEST {
  // delete请求
  dle(url, paramsObj, headersParam = {}) {
    const headers = Object.assign({}, {
      Accept: 'application/json, text/plain, */*',
      'Content-Type': 'application/x-www-form-urlencoded',
    }, headersParam)
    const result = fetch(url, {
      method: 'DELETE',
      credentials: 'include',
      headers,
      body: obj2params(paramsObj),
    });
    return result;
  }
  // 上传文件
  postFile(url, formdata, headersParam = {}) {
    const headers = headersParam;
    const result = fetch(url, {
      method: 'POST',
      headers,
      body: formdata,
    });
    return result;
  }
}

export class STORAGE {
  // 处理本地储存
  setStorage(name, data) {
    // 储存数据为对象
    if (typeof data === 'object') {
      const jsonString = JSON.stringify(data);
      try {
        window.localStorage.setItem(name, jsonString);
      } catch (e) {

      }
    } else if (typeof data === 'number' || typeof data === 'string' || typeof data === 'boolean') {
      // 数据为数字，字符串，布尔
      try {
        window.localStorage.setItem(name, data);
      } catch (e) {

      }
    } else {
      // undefined / function
      message.error('该数据类型不能用于本地存储');
    }
  }
  // 获取本地储存
  getStorage(name) {
    try {
      const data = window.localStorage.getItem(name);
      if (data) {
        // JSON.parse
        return JSON.parse(data);
      }
      return '';
    } catch (e) {
      return ''
    }
  }
  // 删除本地储存
  deleteStorage(name) {
    try {
      window.localStorage.removeItem(name);
    } catch (e) {

    }
  }
  // 登录
}

export const preventXss = {
  removeHtmlTab(tab) {
    return tab.replace(/<[^<>]+?>/g, ''); // 删除所有HTML标签
  },
  // 普通字符转换成转意符
  html2Escape(sHtml) {
    return sHtml.replace(/[<>&"]/g, c => ({
      '<': '&lt;',
      '>': '&gt;',
      '&': '&amp;',
      '"': '&quot;',
    }[c]));
  },
  // &nbsp;转成空格
  nbsp2Space(str) {
    const arrEntities = {
      nbsp: ' ',
    };
    return str.replace(/&(nbsp);/ig, (all, t) => arrEntities[t])
  },
  space2Nbsp(str) {
    return str.replace(/\s/ig, '&nbsp;');
  },
  // 转意符换成普通字符
  escape2Html(str) {
    const arrEntities = {
      lt: '<',
      gt: '>',
      nbsp: ' ',
      amp: '&',
      quot: '"',
    };
    return str.replace(/&(lt|gt|nbsp|amp|quot);/ig, (all, t) => arrEntities[t]);
  },
  // 回车转为br标签
  return2Br(str) {
    return str.replace(/\r?\n/g, '<br />');
  },
  // 去除开头结尾换行,并将连续3次以上换行转换成2次换行
  trimBr(str) {
    str = str.replace(/((\s|&nbsp;)*\r?\n){3,}/g, '\r\n\r\n'); // 限制最多2次换行
    str = str.replace(/^((\s|&nbsp;)*\r?\n)+/g, ''); // 清除开头换行
    str = str.replace(/((\s|&nbsp;)*\r?\n)+$/g, ''); // 清除结尾换行
    return str;
  },
  // 将多个连续空格合并成一个空格
  mergeSpace(str) {
    str = str.replace(/(\s|&nbsp;)+/g, ' ');
    return str;
  },
}
export function deleteNoUseKey(obj) {
  Object.keys(obj).forEach((item) => {
    if (!obj[item]) {
      delete obj[item]
    }
  })
  return obj;
}
function addScript(src = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js') {
  const scriptNode = document.createElement('script');
  scriptNode.src = src;

  return scriptNode;
}
export function getPosition() {
  return new Promise((resolve, reject) => {
    const scriptNode = addScript();
    document.getElementsByTagName('head')[0].appendChild(scriptNode);
    scriptNode.onload = function () {
      resolve(remote_ip_info); // eslint-disable-line
    }
    scriptNode.onerror = function () {
      reject();
    }
  })
}
export function checkAdminUser() {
  const _storage = new STORAGE();
  const userInfo = _storage.getStorage('ReactNews_AdminUserInfo');
  if (userInfo && userInfo.nickName) {
    return
  }
  const CreateHashHistory = createHashHistory
  new CreateHashHistory().push('/login')
}
export function changeTitle(value) {
  document.title = `${value}-小白新闻`;
}

